/**
 * Module dependencies.
 */

var express = require('express'), routes = require('./routes'), user = require('./routes/user'), http = require('http'), path = require('path');

var MongoStore = require('connect-mongo')(express);
var settings = require('./settings');
var flash = require('connect-flash');

var app = express();

// all environments
app.set('port', process.env.PORT || 80);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
	secret : settings.cookieSecret,
	key : settings.db,// cookie name
	cookie : {
		maxAge : 1000 * 60 * 60 * 24 * 30
	},// 30 days
}));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
	app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/api', routes.api);
app.get('/hello', routes.hello);
app.get('/insertTest', function(req, res) {
	res.end("hello,world!");
});
app.get('/users', user.list);

var Nav = require('./models/nav.js');
var nav = Nav.get(function(err, nav) {
	app.locals({
		nav : nav,
	});
});
app.locals({
	title : '明星APP',
});

//if (!module.parent) {
//	http.createServer(app).listen(app.get('port'), function() {
//		console.log('Express server listening on port ' + app.get('port'));
//	});
//}
var cluster = require('cluster');
//var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    console.log('[master] ' + "start master...");

    for (var i = 0; i < numCPUs; i++) {
         cluster.fork();
    }

    cluster.on('listening', function (worker, address) {
        console.log('[master] ' + 'listening: worker' + worker.id + ',pid:' + worker.process.pid + ', Address:' + address.address + ":" + address.port);
    });

} else if (cluster.isWorker) {
    console.log('[worker] ' + "start worker ..." + cluster.worker.id);
 // 工作进程分支，启动服务器 
//    var app = require('./app'); 
////    app.listen(80, function() {
////		console.log('Express server listening on port ' + 80);
////	});
//	http.createServer(function (req, res) {
//		var util = require('util');
//        console.log('worker'+cluster.worker.id+":"+util.inspect(app));
//        res.end('worker'+cluster.worker.id+',PID:'+process.pid);
//    }).listen(80, function() {
//		console.log('Express server listening on port ' + 80);
//	});
	http.createServer(app).listen(app.get('port'), function() {
	console.log('Express server listening on port ' + app.get('port'));
});
}
